package com.simou.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.simou.pojo.Role;
import com.simou.pojo.User;
import com.simou.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;

/*  处理用户相关请求，分为三个模块
    1. 路径转发
    2. AJAX请求
    3. 表单请求
*/

@Controller
public class UserController {
    @Autowired
    RoleController roleController;

    @Autowired
    UserServiceImpl userService;

/*  *****************************************************
    1. 路径转发
    *****************************************************
*/

//  1.1
    @RequestMapping("jsp/user.do")
    public String selectMethod(String method){
        System.out.println("method:"+ method);
        if("query".equals(method)){
            return "forward:getUserList";
        }
        else if("add".equals(method)){
            return "forward:addUser";
        }
        else if("modifyexe".equals(method)){
            return "forward:modifyUser";
        }
        else if("pwdmodify".equals(method)){
            return "forward:verifyOldPassword";
        }
        else if("savepwd".equals(method)){
            return "forward:savepwd";
        }
        return "/";
    }

//  1.2
    @RequestMapping("/jsp/{action}")
    public String toAction(@PathVariable String action){
        return action;
    }
/*  *****************************************************
    2. AJAX请求
    *****************************************************
*/

//  2.1 根据uid填充被修改用户的原信息
    @RequestMapping("/user/modify.do")
    public String modifyUser(String method,int uid,Model model,HttpSession session){
        System.out.println("method:"+method);
        System.out.println("uid:"+uid);
        System.out.println("modifyexe uid:"+uid);
        Object obj = session.getAttribute("userList");
        if(obj!=null){
            List<User> userList = (List<User>) obj;
            for (User user : userList) {
                if (user.getId()==uid){
                    // 将用户信息发送给前端，前端自动填充用户的原数据
                    model.addAttribute("user",user);
                }
            }
        }
        return "usermodify";
    }

//  2.2 验证旧密码
    @RequestMapping("/jsp/verifyOldPassword")
    @ResponseBody
    public String verifyOldPassword(String method,@RequestParam("oldpassword") String oldPassword,HttpSession session) throws JsonProcessingException {
        System.out.println("验证旧密码 method:"+method);
        System.out.println("验证旧密码 oldPassword:"+oldPassword);
        ObjectMapper objectMapper = new ObjectMapper();
        HashMap<String, String> resultMap = new HashMap<>();
        Object obj = session.getAttribute("userSession");
        Class<?> objClass = obj.getClass();
        System.out.println("objClass:"+objClass);
        System.out.println("obj的值为"+obj);

        if(StringUtils.hasLength(oldPassword)){ // 密码不为空
            if(obj!=null){  // session未过期
                // 当前登录用户
                User currentUser = (User) obj;
                if(currentUser.getUserPassword().equals(oldPassword)){  // 旧密码正确
                    resultMap.put("result","true");
                }
                else{
                    resultMap.put("result","false");
                }
            }else{
                resultMap.put("result","sessionerror");
            }
        }
        else{   // 密码不为空
            resultMap.put("result","error");
        }
        return objectMapper.writeValueAsString(resultMap);
    }

//  2.3 验证用户码（是否已经存在）
    @RequestMapping("user/ucexist")
    @ResponseBody
    public String verifyExist(String method,String userCode,HttpSession session) throws JsonProcessingException {
        System.out.println("method:"+method);
        System.out.println("userCode:"+userCode);
        HashMap<String, String> resultMap = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();
        // 若userCode为空或null
        if(!StringUtils.hasLength(userCode)){
            resultMap.put("userCode","empty");
        }
        // 查询是否存在此userCode
        User user = userService.getUser(userCode, null);
        if(user!=null){
            resultMap.put("userCode","exist");
        }
        // 返回json数据
        return objectMapper.writeValueAsString(resultMap);
    }

//  2.4 删除用户
    @RequestMapping("/user/deluser")
    @ResponseBody
    public String deleteUser(String method,long uid) throws JsonProcessingException {
        System.out.println("删除用户 method："+method);
        System.out.println("删除用户 uid："+uid);
        int i = userService.deleteUser(uid);
        HashMap<String, String> resultMap = new HashMap<>();
        resultMap.put("delResult",i>0?"true":"false");
        System.out.println(i>0?"删除成功":"删除失败");
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(resultMap);
    }

/*  *****************************************************
    3. 表单请求
    *****************************************************
*/

//  3.1 查询用户信息
    @RequestMapping("jsp/getUserList")
    public String getUserList(Model model, String pageIndex, String queryname, String queryUserRole, HttpSession session){
        int pageSize = 5;
        int currentPageNo = 1;
        long userRole = 0l;
        if(StringUtils.hasLength(pageIndex)){
            currentPageNo = Integer.parseInt(pageIndex);
        }
        if(StringUtils.hasLength(queryUserRole)){
            userRole = Long.parseLong(queryUserRole);
        }

        // 1.查询数据库中一共有多少个用户
        int totalCount = userService.getUsersCount(userRole,queryname);

        // 2.查询用户信息（根据limit和检索条件）
        // 起始 = (currentPageNo-1)*5      currentPageNo=1: limit 0,5 ;currentPageNo=2: limit 5,5
        List<User> userList = userService.getUsersByLimit((currentPageNo - 1) * 5, pageSize,userRole, queryname);
        List<Role> roleList = roleController.getRoleList();

        // 根据总用户数算出总页数(向上取整)
        int totalPageCount = (int)Math.ceil(new BigDecimal(totalCount).divide(new BigDecimal(pageSize)).doubleValue());

        System.out.println("queryname:" + queryname);
        System.out.println("queryUserRole:" + queryUserRole);
        System.out.println("pageIndex:" + pageIndex);
        System.out.println("用户名：" + queryname);
        System.out.println("用户角色：" + queryUserRole);
        System.out.println("totalPageCount --> " + totalPageCount);
        System.out.println("totalCount --> " + totalCount);
        System.out.println("pageSize --> " + pageSize);
        System.out.println("currentPageNo --> " + currentPageNo);
        System.out.println("roleList --> " + roleList);
        System.out.println("userList --> " + userList);

        model.addAttribute("queryUserName",queryname);
        model.addAttribute("queryUserRole",userRole);
        model.addAttribute("totalPageCount",totalPageCount);
        model.addAttribute("totalCount",totalCount);
        model.addAttribute("pageSize",pageSize);
        model.addAttribute("currentPageNo",currentPageNo);
        model.addAttribute("roleList",roleList);
        model.addAttribute("userList",userList);

        // 将用户列表存储到session中，方便后续使用
        session.setAttribute("userList",userList);

        return "userlist";
    }

//  3.2 修改用户信息
    @RequestMapping("/jsp/modifyUser")
    public String modifyUser(long uid,User user,HttpSession session){
        System.out.println("修改页面---[uid]:"+uid);
        Object obj = session.getAttribute("userSession");
        if(obj!=null){
            // 当前登录用户
            User currentUser = (User) obj;
            user.setModifyBy(currentUser.getId());
        }
        user.setModifyDate(new Timestamp(System.currentTimeMillis()));
        // user里面存放修改的信息
        System.out.println("修改用户---[user]:"+user);
        int i = userService.updateUser(uid, user);
        System.out.println(i>0?"修改成功":"修改失败");
        return "forward:getUserList";
    }

//  3.3 修改密码
    @RequestMapping("/jsp/savepwd")
    public String modifyPassword(String rnewpassword,HttpSession session,Model model){
        Object obj = session.getAttribute("userSession");
        if(obj!=null){
            // 当前登录用户
            User currentUser = (User) obj;
            currentUser.setUserPassword(rnewpassword);
            int i = userService.updateUser(currentUser.getId(), currentUser);
            model.addAttribute("error",i>0?"修改密码成功，请用新密码登录":"修改密码失败，请用旧密码登录");
            return "forward:/login.jsp";
        }
        else {
            model.addAttribute("message","session过期，请重新登录");
            return "pwdmodify";
        }
    }

//  3.4 添加用户
    @RequestMapping("/jsp/addUser")
    public String addUser(User user,HttpSession session){
        Object obj = session.getAttribute("userSession");
        if(obj!=null){
            User currentUser = (User) obj;
            user.setCreatedBy(currentUser.getId());
            user.setCreationDate(new Timestamp(System.currentTimeMillis()));
        }
        System.out.println("addUser 路径的user:"+user);
        int i = userService.addUser(user);
        System.out.println(i>0?"添加成功":"添加失败");
        return "forward:getUserList";
    }

//  3.5 查看用户信息
    @RequestMapping("/user/view")
    public String viewUser(String method,int uid,Model model,HttpSession session){
        System.out.println("method:"+method);
        System.out.println("uid:"+uid);
        // 取出查询用户列表时保存在session的userList,以获取该用户信息
        Object obj = session.getAttribute("userList");
        if (obj!=null){
            List<User> userList = (List<User>) obj;
            for (User user : userList) {
                // 若uid相同，说明查询到用户信息
                if(user.getId()==uid){
                    model.addAttribute("user",user);
                }
            }
        }
        return "userview";
    }
}
